//
//  UISegmentedControl+Block.m
//  YDGJ
//
//  Created by ydcq on 16/7/1.
//  Copyright © 2016年 Galaxy360. All rights reserved.
//

#import "UISegmentedControl+Block.h"
#import <objc/runtime.h>

static void *blockKey = "blockKey";

@implementation UISegmentedControl (Block)

@dynamic valueChangeBlock;

- (void)setValueChangeBlock:(void (^)(NSInteger))valueChangeBlock
{
    [self addTarget:self action:@selector(valueChanged:) forControlEvents:UIControlEventValueChanged];
    objc_setAssociatedObject(self, blockKey, valueChangeBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
    
    [self setUIStyle];
}

- (void)setUIStyle
{
    self.layer.borderColor = WhiteColor.CGColor;
    self.layer.borderWidth = 0.8;
    self.layer.cornerRadius = 3;
    self.layer.masksToBounds = YES;
    [self setBackgroundImage:imageWithColor(Color_Main) forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
    [self setBackgroundImage:imageWithColor(RGB(73, 73, 73)) forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [self setTitleTextAttributes:@{NSForegroundColorAttributeName: WhiteColor} forState:UIControlStateSelected];
    [self setTitleTextAttributes:@{NSForegroundColorAttributeName: WhiteColor} forState:UIControlStateNormal];
    [self setBackgroundImage:imageWithColor([UIColor clearColor]) forState:UIControlStateHighlighted barMetrics:UIBarMetricsDefault];
}

- (void (^)(NSInteger))valueChangeBlock
{
    return objc_getAssociatedObject(self, blockKey);
}

- (void)valueChanged:(UISegmentedControl *)seg
{
    if (self.valueChangeBlock) {
        self.valueChangeBlock(self.selectedSegmentIndex);
    }
}

@end
